import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { useNavStore, useUserStore } from "@/store"
import { NavigationGuardNext, RouteLocationNormalized, RouteLocationNormalizedLoaded, Router, RouteRecordRaw } from "vue-router"
import { appRoutes } from "./modules"
import { routeFilter } from './routeFilter'
import { getMenuList } from '@/http/api/management/menu'
import { IMenuNode } from '@/modules/management/menu'

const getRoutes = async (router: Router) => {
    // 获取全部路由
    const routes:RouteRecordRaw[] = await appRoutes()
    const result:RouteRecordRaw[] = []
    // 按照一级路由顺序重新排列所有路由
    routes!.map((item) =>{
      result[item.meta!.order as number] = item
    })

    // 获取服务器返回菜单权限
    const menuNode = await getMenuList()
    const menuNodes = menuNode.data as IMenuNode[]
    // console.log('menuNodes', menuNodes, menuNode)
    // 过滤出当前角色拥有的路由
    const asyncRoutes = routeFilter(result, menuNodes)
    router.addRoute({path: '/',name: 'Layout', redirect: {name:`${menuNodes[0].node_route}`},component:() => import('@/view/Layout/index.vue'),children: []})
    // 将拥有的路由添加到'Layout'下
    asyncRoutes!.forEach(item => {
      router.addRoute('Layout', item)
    })
    return asyncRoutes
}
let flag: boolean = false
let defaultPath: string = ''
const routeGuard = (router: Router) => {
  router.beforeEach(async (to: RouteLocationNormalized, from: RouteLocationNormalizedLoaded, next: NavigationGuardNext) => {
    NProgress.start()
    const navStore = useNavStore()
    const userStore = useUserStore()
    // 查看所有路由
    if(to.name !== 'login') {
      console.log('to.name', to.name)
      if(userStore.isLogin) {
        if(navStore.routes.length < 1) {
          // console.log('1', 1)
          next('/login')
        }
        if(!flag) {
          // console.log('2', 2)
          const asyncRoutes = (await getRoutes(router)) as RouteRecordRaw[]
          // console.log('asyncRoutes1', asyncRoutes)
          // 保存到仓库
          navStore.setRoutes(asyncRoutes)
          const allroutes = router.getRoutes()
          console.groupCollapsed()
          console.log('allroutes', allroutes)
          console.log('from', from)
          console.groupEnd()

          flag = true
          // 重新跳转此页面
          if (to.matched.length == 0) {
            // console.log('3', 3)
            next({ path: to.path, query: to.query })
          } else {
            if (to.path === '/') {
              // console.log('4', 4)
              defaultPath = asyncRoutes[0].path
              next({ path: defaultPath })
            } else {
              // console.log('5', 5)
              next()
            }
          }
        }
        next()
      } else {
        next('/login')
      }
    } else {
      console.log('to.name', to.name)
      flag = false
      next()
    }
  }),
  router.afterEach(async (to, from) => {
    if(to.fullPath === from.fullPath) {
      await getRoutes(router)
    }
    NProgress.done()
  })
}

export default routeGuard